import requests
from bs4 import BeautifulSoup
import re
from pandas import *


def get_etf_index(fund_code: str) -> str:
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
        'Referer': f'http://fundf10.eastmoney.com/{fund_code}.html'
    }
    try:
        # 访问基金档案页面
        url = f"http://fundf10.eastmoney.com/jbgk_{fund_code}.html"
        response = requests.get(url, headers=headers, timeout=10)
        response.encoding = 'utf-8'
        soup = BeautifulSoup(response.text, 'html.parser')
        performance_benchmark = soup.find('th', string=re.compile('业绩比较基准'))
        if performance_benchmark:
            benchmark_td = performance_benchmark.find_next_sibling('td')
            if benchmark_td:
                index_name = benchmark_td.get_text(strip=True)
                # 清理数据，提取核心指数名称
                # index_name = re.sub(r'×\d+%', '', index_name)  # 去掉权重
                # index_name = re.sub(r'[＋+]', '', index_name)  # 去掉加号
                # index_name = re.sub(r'银行.*?利率', '', index_name)  # 去掉存款利率部分
                return index_name.strip('× ')
        # 方法2：如果上面没找到，尝试其他位置
        fund_info = soup.find('div', class_='detail')
        if fund_info:
            text = fund_info.get_text()
            # 在文本中搜索指数相关关键词
            patterns = [
                r'跟踪标的[：:]\s*([^\\n]+)',
                r'跟踪指数[：:]\s*([^\\n]+)',
                r'标的指数[：:]\s*([^\\n]+)'
            ]
            for pattern in patterns:
                match = re.search(pattern, text)
                if match:
                    return match.group(1).strip()

        return "未找到跟踪指数"

    except Exception as e:
        print(fund_code)
        return f"查询失败: {str(e)}"


# 使用示例
if __name__ == "__main__":
    # 测试几个常见ETF
    test_codes = ["510300", "512880", "515000", "159915"]
    jj_rc3 = read_excel(r'JJ_ETF.xlsx', dtype={'基金代码': str, '基金名称': str})
    for code in jj_rc3['基金代码'].values:
        index_name = get_etf_index(code)
        print(f"{index_name}")
